<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\UserAddress;
use think\Db;

/**
 * 收货地址接口
 */
class Address extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 收货地址列表
     * 
     * @ApiTitle    (收货地址列表)
     * @ApiSummary  (获取用户的收货地址列表)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
     "code": 1,
     "msg": "success",
     "data": [{
       "id": 1,
       "user_id": 1,
       "contact": "张三",        // 收货人
       "phone": "13800138000",  // 联系电话
       "province": "广东省",     // 省份
       "city": "深圳市",        // 城市
       "district": "南山区",    // 区县
       "address": "科技园路1号", // 详细地址
       "is_default": 1,        // 是否默认地址
       "createtime": "2024-01-01 00:00:00"
     }]
     })
     */
    public function index()
    {
        $list = UserAddress::where('user_id', $this->auth->id)
            ->order('is_default DESC, id DESC')
            ->select();
            
        // 格式化时间
        foreach($list as &$item) {
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }
            
        $this->success('', $list);
    }

    /**
     * 添加/编辑收货地址
     * 
     * @ApiTitle    (添加/编辑收货地址)
     * @ApiSummary  (添加或修改收货地址信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=false, description="地址ID，不传则为添加")
     * @ApiParams   (name="contact", type="string", required=true, description="收货人姓名")
     * @ApiParams   (name="phone", type="string", required=true, description="联系电话")
     * @ApiParams   (name="province", type="string", required=true, description="省份")
     * @ApiParams   (name="city", type="string", required=true, description="城市")
     * @ApiParams   (name="district", type="string", required=true, description="区县")
     * @ApiParams   (name="address", type="string", required=true, description="详细地址")
     * @ApiParams   (name="is_default", type="integer", required=false, description="是否默认地址：0=否,1=是")
     * @ApiReturn   ({
     "code": 1,
     "msg": "保存成功",
     "data": null
     })
     */
    public function save()
    {
        $params = $this->request->post();
        
        Db::startTrans();
        try {
            if (!empty($params['is_default'])) {
                // 将其他地址设为非默认
                UserAddress::where('user_id', $this->auth->id)
                    ->update(['is_default' => 0]);
            }
            
            if (!empty($params['id'])) {
                // 修改
                $address = UserAddress::where([
                    'id' => $params['id'],
                    'user_id' => $this->auth->id
                ])->find();
                if (!$address) {
                    $this->error('地址不存在');
                }
                $address->save($params);
            } else {
                // 新增
                $address = new UserAddress;
                $address->user_id = $this->auth->id;
                $address->save($params);
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success('保存成功');
    }

    /**
     * 删除收货地址
     * 
     * @ApiTitle    (删除收货地址)
     * @ApiSummary  (删除指定的收货地址)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="地址ID")
     * @ApiReturn   ({
     "code": 1,
     "msg": "删除成功",
     "data": null
     })
     * 
     */
    public function delete()
    {
        $id = $this->request->post('id');
        
        $address = UserAddress::where([
            'id' => $id,
            'user_id' => $this->auth->id
        ])->find();
        
        if (!$address) {
            $this->error('地址不存在');
        }
        
        $address->delete();
        
        $this->success('删除成功');
    }
}